import requests
import json
import hmac
import hashlib
from collections import OrderedDict
from urllib.parse import quote


def jh_sign(params):
    """
   使用HMAC-SHA256算法签名参数，匹配Java代码逻辑

   参数:
   params -- 字典类型，包含要签名的参数
   secret -- 密钥字符串

   返回:
   大写的十六进制格式HMAC-SHA256签名
   """
    secret = "NP3foR6J"

    # 1. 移除signature参数（如果存在）
    if "signature" in params:
        del params["signature"]

    # 2. 按键名排序参数
    sorted_params = OrderedDict(sorted(params.items()))

    # 3. 拼接成 key=value&key=value... 格式
    query_string = ""
    for key, value in sorted_params.items():
        # 对键值进行URL编码处理，确保特殊字符正确处理
        encoded_key = quote(str(key), safe='')
        encoded_value = quote(str(value), safe='')
        query_string += f"{encoded_key}={encoded_value}&"

    # 去掉末尾的 '&'
    if query_string.endswith('&'):
        query_string = query_string[:-1]

    # 4. HMAC-SHA256 加密
    message = query_string.encode('utf-8')
    secret_bytes = secret.encode('utf-8')

    signature = hmac.new(secret_bytes, message, digestmod=hashlib.sha256)
    return signature.hexdigest().upper()


def jh_login(username, password):
    """
    JH登录函数，获取token
    :param username: JH账号
    :param password: JH密码
    :return: 成功返回token，失败返回None
    """
    try:
        url = "https://admin.jhsrvip.cn/api/wins/login"

        payload = json.dumps({
            "telephone": username,
            "password": password
        })
        headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'Connection': 'keep-alive',
            'Origin': 'https://admin.jhsrvip.cn',
            'Referer': 'https://admin.jhsrvip.cn/login?redirect=UserSettings',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0',
            'sec-ch-ua': '"Not(A:Brand";v="99", "Microsoft Edge";v="133", "Chromium";v="133"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'Content-Type': 'application/json',
            'Host': 'admin.jhsrvip.cn'
        }

        response = requests.request("POST", url, headers=headers, data=payload)
        res = response.json()
        if 'data' in res and 'token' in res['data']:
            token = res['data']['token']
            return token
        else:
            print(f"登录失败: {response.text}")
            return None

    except Exception as e:
        print(f"登录过程中发生异常: {e}")
        return None


# 全局变量用于存储最后一次API调用的响应文本
_last_response_text = ""

def get_coupon_list(couponSeedId, orderNo, quantity, companysk):
    global _last_response_text
    
    payload = {
        "couponSeedId": couponSeedId,
        "orderNo": orderNo,
        "quantity": quantity
    }
    signature = jh_sign(payload)
    url = f"https://admin.jhsrvip.cn/api/wins/api/coupon/pickup?signature={signature}"
    headers = {
        'Authorization': f'Bearer {companysk}',
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'Accept': '*/*',
        'Host': 'admin.jhsrvip.cn',
        'Connection': 'keep-alive',
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=json.dumps(payload))
    
    # 保存响应文本到全局变量
    _last_response_text = response.text
    print(response.text)
    
    try:
        res = response.json()
    except Exception as e:
        coupon_list = []
        cost = 0
        code = 401
        return coupon_list, code, cost
    try:
        res = response.json()
        coupon_list = res['data']['codes']
        cost = res['data']['cost']
        code = 200
        return coupon_list, code, cost
    except Exception as e:
        coupon_list = []
        cost = 0
        code = 403
        return coupon_list, code, cost

def get_last_response_text():
    """获取最后一次API调用的响应文本"""
    global _last_response_text
    return _last_response_text


